import {useState,useEffect} from 'react'
import useStorage from '../useStorage'
import {matchRouterMenus} from '@/utils/index'
import {useLayout} from '@/layout/LayoutProvider'
export const useAuth = (pathname)=>{
  const {state} = useLayout()
  const {menus:routerMenus} = state
  const [auth,setAuth] = useState(-1)//-1初始0不通过1通过
  const [permissions,] = useStorage('permissions')
  useEffect(()=>{
    if(permissions && routerMenus){
      const routerList = matchRouterMenus(pathname,routerMenus)
      if(routerList.length === 0){
        return
      }
      const currentRouter = routerList[routerList.length-1]
      if(!currentRouter.access){
        setAuth(1)
        return
      }
      const authPass = permissions.some(permission=>{
        return permission === '*' || permission.startsWith(currentRouter.access)
      })
      setAuth(authPass?1:0)
    }
  },[permissions,routerMenus,pathname])
  return auth
}
